package services

import (
	"errors"
	"gorm.io/gorm"
	"mishop/entitys"
	"mishop/models"
)

type IUserService interface {
	FindByID(product_id uint) (*models.User, error)
	FindByUserID(page, rows int, category_id uint) (models.Pages, error)
	Register(entity entitys.UserStoreEntity) (*models.User, error)
}
type UserService struct {
	model models.IUser
}

func (p *UserService) Register(entity entitys.UserStoreEntity) (user *models.User, err error) {
	//组装user
	user = &models.User{Openid: entity.Openid, Phone: entity.Phone}
	//查找是否存在
	tempUser, err := p.model.FindByOpenid(user.Openid)
	if err != nil && err != gorm.ErrRecordNotFound{
		return nil, err
	}
	if tempUser.ID > 0 {
		return nil, errors.New("用户已存在")
	}
	//注册
	user, err = p.model.Create(user)
	return
}

func (p *UserService) FindByID(product_id uint) (*models.User, error) {
	return p.model.FindByID(product_id)
}

func (p *UserService) FindByUserID(page, rows int, category_id uint) (models.Pages, error) {
	return p.model.FindByUserID(page, rows, category_id)
}

func NewUserService(model models.IUser) IUserService {
	return &UserService{model: model}
}
